package com.supersit.greensproject.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.google.gson.Gson;
import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.activity.BaseFragment;
import com.supersit.greensproject.adapter.UploadAutoTvAdapter;
import com.supersit.greensproject.entity.BaseBase;
import com.supersit.greensproject.entity.DataUpload;
import com.supersit.greensproject.resources.API;
import com.supersit.greensproject.utils.HttpXUtils;
import com.supersit.greensproject.utils.L;
import com.supersit.greensproject.utils.MyCallBack;
import com.supersit.greensproject.utils.NetWorkInfo;
import com.supersit.greensproject.utils.SPUtils;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.CustomDialog;
import com.supersit.greensproject.view.ShowDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cong on 2016/7/21.
 */
@ContentView(R.layout.fragment_upload_data_entering)
public class UploadDataEnteringFragment extends BaseFragment {
    private Context context;
    private DbManager db;
    @ViewInject(R.id.et_entering_data)
    private EditText etDate;
    @ViewInject(R.id.et_entering_base_name)
    private AutoCompleteTextView etBaseName;
    @ViewInject(R.id.sp_entering_area)
    private Spinner spArea;
    @ViewInject(R.id.et_entering_base_address)
    private EditText etBaseAddress;
    @ViewInject(R.id.et_entering_contacts)
    private EditText etContacts;
    @ViewInject(R.id.et_entering_tel)
    private EditText etTel;
    @ViewInject(R.id.et_entering_output)
    private EditText etOutPut;//产量
    @ViewInject(R.id.sp_entering_quarter)
    private Spinner spQuarter;//季度
    @ViewInject(R.id.et_entering_proportion)
    private EditText etProportion;//面积
    @ViewInject(R.id.et_entering_next_budget)
    private EditText etNextQuarterOutput;//下季度产量
    @ViewInject(R.id.sp_entering_next_date)
    private Spinner spNextUploadDate;//下一次上的v的时间
    @ViewInject(R.id.btn_save_uploadinfo)
    private Button btnSave;
    private int merchandise;//作为种类 0蔬菜 1肉鸡 2奶牛 3塘鱼 4生猪
    String[] columns = new String[]{"baseName", "id", "id as _id"};
    private UploadAutoTvAdapter autoTvAdapter;
    private final int UPLOAD_SUCCESS = 0x10;
    private final int UPLOAD_FAIL = 0x11;
    private final int SERVICE_ERROR = 0x12;
    private ShowDialog showDialog;
    private int baseId;
    private int userId;
    private DataUpload du;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        context = getActivity();
        initVariable();
        bindListener();
    }

    private void initVariable() {
        ArrayAdapter areaAdapter = ArrayAdapter.createFromResource(
                context, R.array.area, R.layout.spinner_text);
        areaAdapter.setDropDownViewResource(R.layout.item_spinner);
        spArea.setAdapter(areaAdapter);
        showDialog = new ShowDialog(context);
        String[] quarter = getResources().getStringArray(R.array.quarter);
        ArrayList<String> nextUploadDateList = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        int year = Integer.parseInt(sdf.format(new Date()));
        for (int i = 0; i < 8; i++) {
            if (i < 4) {
                nextUploadDateList.add(year + quarter[i]);
            } else {
                nextUploadDateList.add((year + 1) + quarter[i - 4]);
            }
        }
        ArrayAdapter quarterAdapter = new ArrayAdapter(context, R.layout.spinner_text, nextUploadDateList);
        quarterAdapter.setDropDownViewResource(R.layout.item_spinner);
        spQuarter.setAdapter(quarterAdapter);
        ArrayAdapter<String> nextUploadDateAdapter = new ArrayAdapter<String>(context, R.layout.spinner_text, nextUploadDateList);
//        ArrayAdapter nextUploadDateAdapter = ArrayAdapter.createFromResource(
//                context, nextUploadDate, R.layout.spinner_text);
        nextUploadDateAdapter.setDropDownViewResource(R.layout.item_spinner);
        spNextUploadDate.setAdapter(nextUploadDateAdapter);
        etDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        merchandise = getActivity().getIntent().getIntExtra("merchandise", 0);
        /**设置字符数*/
        etBaseName.setThreshold(1);
        autoTvAdapter = new UploadAutoTvAdapter(context, null, 0, columns, merchandise);
        etBaseName.setAdapter(autoTvAdapter);
        spArea.setEnabled(false);
        spArea.setClickable(false);
        db = XUtilsDbManager.getInstance();
        userId = (int) SPUtils.get(context, "userId", 0);
    }

    private void bindListener() {
        btnSave.setOnClickListener(onClickListener);
        etBaseName.setOnItemClickListener(onItemClickListener);
        etBaseName.addTextChangedListener(textWatcher);
        // etNextUploadDate.setOnTouchListener(onTouchListener);
    }

    private boolean checkData() {
        boolean flag = false;
        if (TextUtils.isEmpty(etDate.getText().toString().trim())) {
            T.showShort(context, R.string.maket_create_is_null);
            return flag;
        }
        if (TextUtils.isEmpty(etBaseName.getText().toString().trim())) {
            T.showShort(context, R.string.base_name_not_null);
            return flag;
        }
//        if (TextUtils.isEmpty(etBaseAddress.getText().toString().trim())) {
//            T.showShort(context, R.string.base_address_is_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etContacts.getText().toString().trim())) {
//            T.showShort(context, R.string.base_contacts_is_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etTel.getText().toString().trim())) {
//            T.showShort(context, R.string.base_tel_is_null);
//            return flag;
//        }
        if (TextUtils.isEmpty(etOutPut.getText().toString().trim())) {
            T.showShort(context, R.string.base_output_is_null);
            return flag;
        }
//        if (TextUtils.isEmpty(etProportion.getText().toString().trim())) {
//            T.showShort(context, R.string.base_aera_is_null);
//            return flag;
//        }
        if (TextUtils.isEmpty(etNextQuarterOutput.getText().toString().trim())) {
            T.showShort(context, R.string.next_quarter_output_is_null);
            return flag;
        }
        if (baseId == 0) {
            T.showShort(context, R.string.select_base_error);
            return flag;
        }
        flag = true;
        return flag;
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_save_uploadinfo:
                    if (checkData()) {
                        String date = TextUtils.isEmpty(etDate.getText().toString()) ? "" : etDate.getText().toString().trim();
                        String baseName = TextUtils.isEmpty(etBaseName.getText().toString()) ? "" : etBaseName.getText().toString().trim();
                        int areaId = spArea.getSelectedItemPosition();
                        String baseAddress = TextUtils.isEmpty(etBaseAddress.getText().toString()) ? "" : etBaseAddress.getText().toString().trim();
                        String contacts = TextUtils.isEmpty(etContacts.getText().toString()) ? "" : etContacts.getText().toString().trim();
                        String tel = TextUtils.isEmpty(etTel.getText().toString()) ? "" : etTel.getText().toString().trim();
                        String output = TextUtils.isEmpty(etOutPut.getText().toString()) ? "" : etOutPut.getText().toString().trim();
                        String quarter = TextUtils.isEmpty((String) spQuarter.getSelectedItem()) ? "" : (String) spQuarter.getSelectedItem();
                        String proportion = TextUtils.isEmpty(etProportion.getText().toString()) ? "" : etProportion.getText().toString().trim();
                        String nextOutput = TextUtils.isEmpty(etNextQuarterOutput.getText().toString()) ? "" : etNextQuarterOutput.getText().toString().trim();
                        String nextDate = TextUtils.isEmpty((String) spNextUploadDate.getSelectedItem()) ? "" : (String) spNextUploadDate.getSelectedItem();
                        du = new DataUpload();
                        du.setCreateDate(date);
                        du.setBaseName(baseName);
                        du.setBaseAddress(baseAddress);
                        du.setArea(areaId);
                        du.setContacts(contacts);
                        du.setTel(tel);
                        du.setOutput(output);
                        du.setQuarter(quarter);
                        du.setProportion(proportion);
                        du.setEstimatedOutput(nextOutput);
                        du.setEstimatedUploadDate(nextDate);
                        du.setIsDelete(1);
                        du.setOperationsTatus(1);
                        du.setMerchandise(merchandise);
                        du.setBaseId(baseId);
                        du.setUserId(userId);
                        try {
                            if (NetWorkInfo.isNetworkAvailable(context)) {
                                //上传数据
                                dataUpload(du);
                            } else {
                                //无网络，保存本地
                                du.setIsUpload(1);
                                db.saveBindingId(du);
                                clearView();
                                T.showShort(context, R.string.unnetwork_save_locality);
                            }

                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }

        }
    };

    private void clearView() {

        baseId = 0;
        // etDate.setText("");

        etBaseName.setText("");

        spArea.setSelection(0);

        etBaseAddress.setText("");

        etContacts.setText("");

        etTel.setText("");

        etOutPut.setText("");//产量

        spQuarter.setSelection(0);//季度

        etProportion.setText("");//面积

        etNextQuarterOutput.setText("");//下季度产量

        spNextUploadDate.setSelection(0);//下一次上的v的时间
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int bId = (int) view.getTag();
            try {
                BaseBase bs = db.selector(BaseBase.class).where("id", "=", bId).findFirst();
                if (null != bs) {
                    if (bs.getOperationsTatus() == -1) {
                        spArea.setSelection(bs.getAreaId());
                        etBaseAddress.setText(bs.getBaseAddress() == null ? "" : bs.getBaseAddress());
                        etContacts.setText(bs.getContacts() == null ? "" : bs.getContacts());
                        etTel.setText(bs.getTel() == null ? "" : bs.getTel());
                        etProportion.setText(bs.getProportion() == null ? "" : bs.getProportion());
                        baseId = bs.getBaseId();
                    } else {
                        CustomDialog dialog;
                        CustomDialog.Builder customBuilder = new CustomDialog.Builder(
                                context);
                        customBuilder
                                .setTitle(R.string.warning)
                                .setMessage(R.string.base_statu_is_synchorization)
                                .setNegativeButton(R.string.ok,
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                                int which) {
                                                etBaseName.setText("");
                                                dialog.dismiss();
                                            }
                                        });
                        dialog = customBuilder.create();
                        dialog.show();
                    }

                }
                L.d(bs.getBaseName());
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    };
    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
//            DatePickDialog datePickDialog = new DatePickDialog(context, new DatePickDialog.IgetDate() {
//                @Override
//                public void getDate(int i, int i1, int i2) {
//
//                }
//            }, "选择日期", "确定", "取消");
//
//            datePickDialog.show();
//            if (motionEvent.getAction() == KeyEvent.ACTION_DOWN) {
//                Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
//                DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
//                    @Override
//                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
//                        etNextUploadDate.setText(i + "-" + (i1 + icv1) + "-" + i2);
//                    }
//                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE));
//                datePickerDialog.show();
//            }

            return false;
        }
    };

    /**
     * 数据上报
     */
    private void dataUpload(final DataUpload dataUpload) {
        String url = API.UploadAndUpdateUploadDada;
        Map<String, Object> map = new HashMap<>();
        Gson gson = new Gson();
        String str = gson.toJson(dataUpload);
        map.put("dataReportItem", str);
        showDialog.showLoadingDialog(getString(R.string.uploading_data));
        Callback.Cancelable cancelable = HttpXUtils.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                L.e("Request Error:" + ex.getMessage());
                showDialog.dismissLoadDialog();
                Message message = new Message();
                message.what = SERVICE_ERROR;
                handler.sendMessage(message);
            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                showDialog.dismissLoadDialog();
                L.d("Request result:" + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int isflog = json.optInt("isflog");//1成功  0失败
                    if (isflog == 1) {
                        int uploadDataId = json.optInt("id");
                        long timestamp = json.optLong("timestamp");
                        dataUpload.setUploadDataId(uploadDataId);
                        dataUpload.setTimeStamp(timestamp);
                        dataUpload.setIsUpload(0);//0已上传 1未上传
                        dataUpload.setOperationsTatus(-1);
                        db.saveOrUpdate(dataUpload);
                        Message message = new Message();
                        message.what = UPLOAD_SUCCESS;
                        handler.sendMessage(message);
                    } else {
                        Message message = new Message();
                        message.what = UPLOAD_FAIL;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    showDialog.dismissLoadDialog();
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = SERVICE_ERROR;
                    handler.sendMessage(message);
                } catch (DbException e) {
                    showDialog.dismissLoadDialog();
                    Message message = new Message();
                    message.what = SERVICE_ERROR;
                    handler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        });

        System.out.print(str);
        L.d(str);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    clearView();
                    T.showShort(context, R.string.save_ok);
                    try {
                        du.setIsDelete(0);
                        db.saveBindingId(du);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    break;
                case UPLOAD_FAIL:
                    T.showShort(context, R.string.save_fail);
                    break;
                case SERVICE_ERROR:
                    T.showShort(context, R.string.service_error);
                    break;
            }
        }
    };
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            baseId = 0;
            spArea.setSelection(0);
            etBaseAddress.setText("");
            etProportion.setText("");//面积
            etContacts.setText("");
            etTel.setText("");
        }


        @Override
        public void afterTextChanged(Editable s) {

        }
    };
}
